#coding=utf-8

#from datareport.models import *
from django.db.models import Count
from db_manager import DBManager 
from redisManager import RedisManager
from config import *
from tool import Tool
import datetime
import json
import time
import sys
sys.path.append("mess/demo/")
from mess.demo.send import *
class MerchantManager(object):
    
    def __init__(self,cfgParam,requests):
        self.cfgParam = cfgParam
        self.manager = DBManager(db,ip,ur,pd)
        self.manager.connect()
        self.tool = Tool()
        self.requests = requests
        self.redisM = RedisManager()
        self.redisM.conn()
    def request_sms(self):
        mustkeys = ["mobile"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
	mobile = self.cfgParam["mobile"]
	sms = self.tool.createPhoneCode()
        sendTemplateSMS(mobile,[sms,'60'],1)   
        self.requests.session[mobile] = sms
        return {}
    def verif_sms(self):

        mustkeys = ["sms","mobile"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
	session_sms = self.requests.session.get(self.cfgParam["mobile"],None)
	condition = {"mobile":self.cfgParam["mobile"]}
	result = self.manager.smartQuery(merchant_info,condition)
	if not result :
            ret["status"] = 0
	    ret["info_code"] = 10002
	
	if session_sms != self.cfgParam["sms"]:
	    ret["status"] = 0
	    ret["info_code"] = 10003
        ret["result"] = {"merchantid":result[0]["merchantid"]}	

        return ret
    '''
    def register_merchant(self):
        
	""" 注册商户同时默认注册一个未分组的门店"""
        mustkeys = ["merchantname","username","mobile","password","IDcard"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret

        try:
	    nowtime = time.strftime('%Y-%m-%d',time.localtime(time.time()))
            newmerchantinfo = {
                    "merchantname":self.cfgParam["merchantname"],
                    "username" :self.cfgParam["username"],
                    "mobile"   :self.cfgParam["mobile"],
                    "password"   :self.cfgParam["password"],
                    "IDcard"   :self.cfgParam["IDcard"],
		    "updatetime": nowtime,
                   } 
            is_register = self.manager.smartInsert(merchant_info,newmerchantinfo) 
	    if is_register:
	        mobile = self.cfgParam["mobile"].encode("utf-8")
	        qry_new_info = {
		    "mobile":mobile
		}
                result = self.manager.smartQuery(merchant_info,qry_new_info)
		#查询新注册商户的id
		merchantid = result[0]["merchantid"]
                newstoreinfo = {
		    "merchantid":merchantid,
		    "storename":"未分组",
		    "is_defaultgroup":1

		    }
                self.manager.smartInsert(store_info,newstoreinfo)


                ret['status'] = 1
		ret['info_code'] =  10000
	    else:
                ret['status'] = 0
		ret['info_code'] = 10004
		ret['info'] = 'mobile or IDcard has exists'
               
        except Exception,e:
	    print e
            ret = {'status' : 0,'info_code' :10003 }    
        return ret 
    '''
    def add_StoreToMachant(self):
        "创建门店"
        mustkeys = ["merchantid","storename","address","start_time","end_time"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret

        try:
            info = {
                    "merchantid":self.cfgParam["merchantid"],
                    "storename" :self.cfgParam["storename"],
                    "address"   :self.cfgParam["address"],
		    "start_time":self.cfgParam["start_time"],
		    "end_time":self.cfgParam["end_time"],
                   } 
            self.manager.smartInsert(store_info,info) 
            ret = {'status' : 1}
        except Exception,e:
            ret = {'status' : 0,'errinfo' : e}    
        return ret 

    def update_StoreDetail(self):
        "更爱门店详情信息 "
        mustkeys = ["merchantid","storeid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
	storeid = int(self.cfgParam["storeid"])
	merchantid = int(self.cfgParam["merchantid"])
	if self.cfgParam.has_key("mids"):
	    try :
                mids = self.cfgParam["mids"].split(",")
		
	        info = {"merchantid":merchantid,"is_defaultgroup":1}
                mids_str = ",".join(mids)
		print mids_str
	        result = self.manager.smartQuery(store_info,info)
	        nongroup_storeid = result[0]["storeid"]
	        update_sql = "update %s set storeid = %s where mid in (%s)" %(machine_relation,nongroup_storeid,mids_str)
	        self.manager.execute(update_sql)
            except Exception,e:
	        print e
		ret["status"] = 0
		ret["info_code"] = 10003

	if self.cfgParam.has_key("details"):
	    details = json.loads(self.cfgParam["details"])
	    info = {'storeid':storeid}
	    ret["status"] = self.manager.smartUpdate(store_info,details,info)
            print '9______________________'

        return ret
    def bind_MachineToOther(self):
        mustkeys = ["merchantid","storeid","mid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        #mids = json.loads(mid) 
        try:
            condition = {"mid"       :int(self.cfgParam["mid"])}
            info      = {"storeid"   :int(self.cfgParam["storeid"]),
                         "mid"       :int(self.cfgParam["mid"])
                      }
            if self.manager.smartQuery(machine_relation,condition):
                self.manager.smartUpdate(machine_relation,info,condition)
                print "更新成功!" 
                ret["status"] = 1
	    else:
                self.manager.smartInsert(machine_relation,info)
                print "添加成功!" 
                ret["status"] = 1
            
        except Exception,e:
            print e
            ret['info']=e
            ret['errcode'] = 10003
        return ret 

    def del_StoreFromMachant(self):
        mustkeys = ["storeid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        storeid = self.cfgParam["storeid"]
        execsql = "update  %s set store_status = 0 where storeid = %d and is_defaultgroup != 1" %(store_info,storeid)
        ret = self.manager.excute(execsql)
        if ret:
            ret["status"] = 1
        else:
            ret["info_code"] = 10003
        return ret

    def query_machine_all_tradepackage(self):
        
        #为客户端机器查询全部收费套餐
        mustkeys = ["mid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        #判断当前的时间返回对应的套餐
	mid = int(self.cfgParam["mid"])
        tradekey = "%s%d"%(base_midtradekey,mid)
        tradeinfo = self.redisM.rds.hgetall(tradekey)
	if tradeinfo:
            tradeinfoBydatetype = eval(tradeinfo)
        else:
            tradepackagelist = list(self.manager.smartQuery(trade_package,{}))
	    ret["result"] = tradepackagelist
            return ret
        special=tradeinfoBydatetype["special"]
        default=tradeinfoBydatetype["default"]
        #当前时间
        nowtime = time.strftime("%H:%M:%S") ##24小时格式
        trade = list()
	#判断时间段是否属于特殊时间
        for row in special :
            if nowtime >row["start_time"] and nowtime<row["end_time"]:
	        trade = row["trade"]
	        break
	#常规时间	
        if not trade :	    
            trade = default["trade"] 
	ret["result"] =  trade
        return ret

    def query_machine_tradepackage(self):
        #为客户端机器查询收费套餐
        mustkeys = ["mid"]
	print '222222'
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
	print 'zzzzzzzzzzzzzzzzzz'
        #判断当前的时间返回对应的套餐
	mid = int(self.cfgParam["mid"])
        daytype = self.tool.judge_daytype()
        #daytype = self.tool.judgeDaytype()
        tradekey = "%s%d"%(base_midtradekey,mid)
        tradeinfo = self.redisM.rds.hgetall(tradekey)
	if tradeinfo:
            tradeinfoBydatetype = eval(tradeinfo[daytype])
        else:
            tradepackagelist = list(self.manager.smartQuery(trade_package,{}))
	    ret["result"] = tradepackagelist
            return ret
        special=tradeinfoBydatetype["special"]
	print '1-________________________'
	print mid
	print special
        default=tradeinfoBydatetype["default"]
	print '2___________________'
	print default
        #当前时间
        nowtime = time.strftime("%H:%M:%S") ##24小时格式
        trade = list()
	#判断时间段是否属于特殊时间
        for row in special :
            if nowtime >row["start_time"] and nowtime<row["end_time"]:
	        trade = row["trade"]
	        break
	#常规时间	
        if not trade :	    
            trade = default["trade"] 
	ret["result"] =  trade
	print '3________'
	print ret
        return ret

    def query_tradepackage(self):
        #系统默认套餐信息
        tradepackagelist = list(self.manager.smartQuery(trade_package,{}))
        default  = {"default":{"trade":tradepackagelist},"special":[{'status':1,'start_time':'09:00','end_time':'19:00','trade':tradepackagelist}]} 
        param = {"weekday":default,"weekend":default}
        queryIdTradeinfo = {}
	#查询店面套餐
        if self.cfgParam.has_key("storeid"):
            storeid = int(self.cfgParam["storeid"])
            #机器收费管理key
            queryIdTradekey = "%s%d"%(base_storeidtradekey,storeid)
            queryIdTradeinfo = self.redisM.rds.hgetall(queryIdTradekey) 
            if not queryIdTradeinfo:
                self.redisM.rds.hmset(queryIdTradekey,param)
                queryIdTradeinfo = self.redisM.rds.hgetall(queryIdTradekey)
	
	    for row in queryIdTradeinfo :
	        try:
	            queryIdTradeinfo[row] = eval(queryIdTradeinfo[row])
                except Exception,e:
	            print e
        #查询机器套餐
        if self.cfgParam.has_key("mid"):
	    
            mid = int(self.cfgParam["mid"])
            #机器收费管理key
            queryIdTradekey = "%s%d"%(base_midtradekey,mid)
            queryIdTradeinfo = self.redisM.rds.hgetall(queryIdTradekey) 
            if not queryIdTradeinfo:
                self.redisM.rds.hmset(queryIdTradekey,param)
                queryIdTradeinfo = self.redisM.rds.hgetall(queryIdTradekey)
	
	    for row in queryIdTradeinfo :
	        try:
	            queryIdTradeinfo[row] = eval(queryIdTradeinfo[row])
                except Exception,e:
	            print e


        return queryIdTradeinfo
    def update_tradepackage(self):
        mustkeys = ["storeid","packages"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        storeid  = int(self.cfgParam["storeid"])
	#接收门店收费设置    
        packages = self.cfgParam["packages"]
        try :
            packages = json.loads(packages)
        except Exception,e:
            ret={"status":0,"info":e,"info_code":10002}
            return ret

	#根据门店号 查询关联机器号
        mids_relation_result = self.manager.smartQuery('machine_relation',{'storeid':storeid})	
	for row in mids_relation_result:
	    print row["mid"]
	    #修改机器收费设置
            mid_tradekey = "%s%d"%(base_midtradekey,row["mid"])
            hmset_mid = self.redisM.rds.hmset(mid_tradekey,packages)
        #修改门店收费设置
        storeid_tradekey = "%s%d"%(base_storeidtradekey,storeid)
        hmset_result = self.redisM.rds.hmset(storeid_tradekey,packages)
        store_tradeinfo = self.redisM.rds.hgetall(storeid_tradekey)
	#redis查询获得信息序列化    
	for row in store_tradeinfo :
	    try:
	        store_tradeinfo[row] = eval(store_tradeinfo[row])
            except Exception,e:
	        print e
        ret["result"] = store_tradeinfo
        return ret
    	
if __name__ == "__main__":
    print 1
